
import { _decorator, Component, Node, RigidBody2D, input, Input, EventKeyboard, KeyCode, Vec2, Prefab, instantiate, Sprite } from 'cc';
import { BaseItem2D } from './BaseItem2D';
import { Bullet } from './bullet/Bullet';
import { CollisionObj } from './game/CollisionObj';
import { Main } from './Main';
import { MouseInput } from './Player/MouseInput';
const { ccclass, property } = _decorator;


@ccclass('Player')
export class Player extends BaseItem2D {
    private _keyDownSet=new Set()
    @property({type:Prefab})
    bulletPrefab:Prefab=null
    @property({type:MouseInput})
	private mouseInput:MouseInput
    private tmpVec:Vec2=new Vec2()
    collisionObj:CollisionObj=new CollisionObj(this,30,30)
    
    direction=new Vec2(1,0)

    bulletTimer=10
    private skinNode:Node
    start () {
        this.skinNode=this.node.getChildByName('skin')
        input.on(Input.EventType.KEY_DOWN,this._onKeyDown,this) 
        input.on(Input.EventType.KEY_UP,this._onKeyUp,this)
    }
    private _onKeyDown(e:EventKeyboard){
        this._keyDownSet.add(e.keyCode)
    }
    private _onKeyUp(e:EventKeyboard){
        this._keyDownSet.delete(e.keyCode)
    }
    private isKeyDown(keyCode){
        return this._keyDownSet.has(keyCode)
    }   
    
    loop(){
        let vec2:Vec2=null
        let mouseDir=this.mouseInput.getDir()
        if(mouseDir){
            vec2=this.tmpVec
            vec2.set(mouseDir)
        }else{
            let px = 0
            let py = 0
            if (this.isKeyDown(KeyCode.KEY_A)) {
                px--
            }
            if (this.isKeyDown(KeyCode.KEY_D)) {
                px++
            }
            if (this.isKeyDown(KeyCode.KEY_W)) {
                py++
            }
            if (this.isKeyDown(KeyCode.KEY_S)) {
                py--
            }
            vec2=this.tmpVec
            vec2.set(px,py)
        }
        if(vec2 && Vec2.len(vec2)>0){
            vec2.normalize().multiplyScalar(4)
            this.setPos(this.x+vec2.x,this.y+vec2.y) //移动
            //朝向
            this.direction.set(vec2).normalize()
            Main.I.testMessage.string=String(this.direction)
        }
        this.skinNode.setScale(this.direction.x>=0?1:-1,1)    
    
        //发射子弹
        this.bulletTimer--
        if(this.bulletTimer<=0){
            this.bulletTimer=20
            this.shot()
        }
    }
    shot(){
        let node=instantiate(this.bulletPrefab)
        node.getComponent(Bullet).init(this.x,this.y,this.direction)
    }

}

